<template>
  <page-view class="page-view" :title="false">
    <div slot="headerContent">
      <a-breadcrumb class="s-breadcrumb">
        <a-breadcrumb-item>资产管理</a-breadcrumb-item>
        <a-breadcrumb-item><a @click="goback">物品管理</a></a-breadcrumb-item>
        <a-breadcrumb-item>物品详情</a-breadcrumb-item>
      </a-breadcrumb>
    </div>

    <a-card class="s-card">
      <a-spin :spinning="sending">
        <a-row class="header-container" :gutter="12">
          <a-col :lg="20" :xs="24">
            <a-row :gutter="0">
              <a-col v-for="({ key, label }) in headerData" :key="label" :lg="12" :sm="24">
                <a-form-item :label="label" v-bind="formItemLayout" class="label-width-auto form-item-height">
                  <div v-if="!editable || /quantity|areaQty/.test(key)" class="textOverflow">
                    <span v-if="key !== 'categories'">{{ itemData[key] || (/quantity|areaQty/.test(key) ? 0 : '暂无') }}</span>
                    <span v-else>{{ $get(itemData, key, []).map((i, k) => $get([firTypeMaps, secTypeMaps][k], `${i}.name`, '')).join(' > ') }}</span>
                    <span v-if="!(/quantity|areaQty/.test(key))" class="primary-link" @click="handleEdit(key)">编辑</span>
                  </div>
                  <div v-else class="editing">
                    <a-cascader
                      v-if="/categories/.test(key)"
                      v-model="tempValue[key]"
                      :allow-clear="false"
                      not-found-content="没有数据"
                      :options="firTypeList"
                      :display-render="({ labels }) => labels.join(' > ')"
                      :field-names="{ label: 'name', value: 'id', children: 'children' }"
                      placeholder="请选择分类"
                      style="width: 100%"
                    />
                    <a-input v-else v-model="tempValue[key]" />
                  </div>
                </a-form-item>
              </a-col>
            </a-row>
          </a-col>
          <a-col :lg="4" :sm="8" :xs="10">
            <a-upload
              class="image-container"
              accept="image/*"
              list-type="picture-card"
              :show-upload-list="false"
              :before-upload="beforeUpload"
              :custom-request="handleUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" style="width: 100%" alt="">
              <div v-else>
                <a-icon :type="sending ? 'loading' : 'plus'" />
                <div class="ant-upload-text">上传</div>
              </div>
            </a-upload>
          </a-col>
        </a-row>

        <div class="btn-container">
          <a-button @click="editCount">修改库存</a-button>
          <a-button @click="handleExport">导出物品日志</a-button>
          <a-button v-show="editable" class="primary-btn" style="margin-left: 20px" @click="handleSave">保存</a-button>
          <a-button v-show="editable" @click="handleCancel">取消</a-button>
        </div>

        <a-tabs animated type="card" @change="tabchange">
          <a-tab-pane key="0" tab="物品日志">
            <s-table
              ref="logTable"
              class="s-table"
              bordered
              row-key="id"
              :locale="{ emptyText: '暂无数据' }"
              :show-pagination="false"
              :columns="logColumns"
              :data="logLoadData"
              :alert="false"
            >
              <template slot="action" slot-scope="item">
                <div class="action-container">
                  <span class="primary-link" style="padding-right: 0;" @click="checkPDF(item)">查看申请单</span>
                  <span v-if="item.ridType==='入库'" class="primary-link" @click="checkQrcode(item)">查看二维码</span>
                </div>
              </template>
            </s-table>
            <!-- 分页器 -->
            <div class="pagination-container">
              <a-pagination
                :page-size="queryParam.pageSize"
                :show-total="total => `共 ${total} 条记录 第 ${queryParam.pageNum} / ${Math.ceil(total / queryParam.pageSize)} 页`"
                :current="queryParam.pageNum"
                :total="count"
                hide-on-single-page
                show-quick-jumper
                @change="handlePage"
              />
            </div>
          </a-tab-pane>
          <a-tab-pane key="1" tab="物品情况">
            <s-table
              ref="infoTable"
              class="s-table"
              bordered
              row-key="id"
              :locale="{ emptyText: '暂无数据' }"
              :show-pagination="false"
              :columns="infoColumns"
              :data="infoLoadData"
              :alert="false"
              style="margin-bottom: 12px;"
            >
              <template slot="areaName" slot-scope="item">
                <span v-if="$get(areaMaps, `${item.areaPid}.name`, '')">{{ $get(areaMaps, `${item.areaPid}.name`, '') }} > </span>
                <span>{{ item.areaName }}</span>
              </template>
              <template slot="action" slot-scope="item">
                <div class="action-container">
                  <a-dropdown>
                    <a-menu slot="overlay">
                      <a-menu-item @click="handleAction(item, 0)">报废</a-menu-item>
                      <a-menu-item class="danger-link" @click="handleAction(item, 1)">转移</a-menu-item>
                    </a-menu>
                    <span class="primary-link">选择操作</span>
                  </a-dropdown>
                </div>
              </template>
            </s-table>
          </a-tab-pane>
        </a-tabs>

        <div style="width: 100%; text-align: center;">
          <a-button @click="goback">返回</a-button>
        </div>

        <PDFModal
          :url="url"
          :file-name="fileName"
          :visible="showPDF"
          :title="modalTitle"
          :extra-text="modalText"
          @cancel="showPDF = false"
        />

        <a-modal
          v-model="showElse"
          title="其他库存情况"
          :footer="null"
          centered
        >
          <a-form v-if="target" class="filter">
            <a-row>
              <a-form-item label="库存类型" v-bind="formItemLayout" class="label-width-auto">{{ target.type }}</a-form-item>
              <a-form-item label="关联表单" v-bind="formItemLayout" class="label-width-auto">{{ target.linkType || '无' }}</a-form-item>
              <a-form-item label="库存变化" v-bind="formItemLayout" class="label-width-auto">{{ /^-/.test(target.changeCount) ? '减少' : '增加' }}</a-form-item>
              <a-form-item label="变化数量" v-bind="formItemLayout" class="label-width-auto">{{ $get(target, 'changeCount', '').replace('-', '') }}</a-form-item>
              <a-form-item label="变化后库存量" v-bind="formItemLayout" class="label-width-auto">{{ target.count }}</a-form-item>
              <a-form-item label="备注" v-bind="formItemLayout" class="label-width-auto">{{ target.remark }}</a-form-item>
            </a-row>
          </a-form>
        </a-modal>

        <!-- 修改库存弹窗 -->
        <a-modal
          v-model="showEdit"
          title="修改库存"
          centered
        >
          <a-form :form="form">
            <a-form-item label="库存类型" v-bind="formItemLayout" class="label-width-auto">
              <a-select
                v-decorator="[
                  'type',
                  { rules: [{ required: true, type: 'string', message: '请选择' }] },
                ]"
                :options="['报废', '其他'].map(value => ({ label: value, value }))"
                @change="typeChange"
              />
            </a-form-item>
            <a-form-item label="库存变化" v-bind="formItemLayout" class="label-width-auto">
              <a-radio-group
                v-decorator="[
                  'attr',
                  { rules: [{ required: true, message: '请选择' }], initialValue: 0 },
                ]"
                :options="[
                  { value: 0, label:'减少' },
                  { value: 1, label: '增加', disabled: form.getFieldValue('type') === '报废' }
                ]"
              />
            </a-form-item>
            <a-form-item label="变化数量" v-bind="formItemLayout" class="label-width-auto">
              <a-input-number
                v-decorator="[
                  'quantity',
                  { rules: [{ required: true, type: 'number', message: '请输入' }], initialValue: 1 },
                ]"
                class="width-fix"
                :min="1"
                :max="form.getFieldValue('attr') < 1 && itemData.quantity > 0 ? itemData.quantity : 10000000000000000"
                placeholder="请输入"
              />
            </a-form-item>
            <a-form-item label="备注" v-bind="formItemLayout" class="label-width-auto">
              <a-textarea
                v-decorator="[
                  'remark',
                  { rules: [{ required: form.getFieldValue('type') === '其他', type: 'string', message: '请输入备注', whitespace: true }] }
                ]"
                placeholder="请输入备注"
                style="resize: none"
              />
            </a-form-item>
          </a-form>

          <template slot="footer">
            <a-button key="back" @click="showEdit = false">取消</a-button>
            <a-button key="submit" type="primary" :loading="sending" @click="handleOk">
              确定
            </a-button>
          </template>
        </a-modal>
        <!-- 修改库存弹窗 end -->

        <!-- 操作弹窗 -->
        <a-modal
          v-model="showMove"
          :title="`${['报废', '移交'][moveType]}物品`"
          centered
        >
          <a-form :form="moveForm">
            <a-form-item label="库存类型" v-bind="formItemLayout">{{ ['报废', '移出'][moveType] }}</a-form-item>
            <a-form-item :label="`${['报废', '移出'][moveType]}数量`" v-bind="formItemLayout">
              <a-input-number
                v-decorator="[
                  'quantity',
                  { rules: [{ required: true, type: 'number', message: '请输入' }], initialValue: 1 },
                ]"
                class="width-fix"
                :min="1"
                :max="$get(target, 'quantity', 0)"
                placeholder="请输入"
              />
            </a-form-item>
            <a-form-item v-if="moveType > 0" label="转移区域" v-bind="formItemLayout">
              <a-cascader
                v-decorator="[
                  'areaId',
                  { rules: [{ required: true, type: 'array', message: '请选择转移区域' }] },
                ]"
                not-found-content="没有数据"
                :options="deptAreaList"
                :display-render="({ labels }) => labels.join(' > ')"
                :field-names="{ label: 'name', value: 'id', children: 'children' }"
                placeholder="请选择转移区域"
              />
            </a-form-item>
            <a-form-item v-if="moveType > 0" label="负责部门" v-bind="formItemLayout">
              <a-select
                v-decorator="[
                  'deptId',
                  { rules: [{ required: true, type: 'number', message: '请选择负责部门' }] },
                ]"
                placeholder="请选择部门"
              >
                <a-select-option
                  v-for="item in deptList"
                  :key="item.deptId"
                  :value="item.deptId"
                >{{ item.deptName }}</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item v-if="moveType > 0" label="负责人员" v-bind="formItemLayout">
              <a-cascader
                v-decorator="[
                  'userId',
                  { rules: [{ required: true, message: '请选择负责人' }] },
                ]"
                :disabled="!moveForm.getFieldValue('deptId')"
                not-found-content="没有数据"
                :options="$get(deptListMaps, moveForm.getFieldValue('deptId'), [])"
                :display-render="({ labels }) => labels.pop()"
                :field-names="{ label: 'name', value: 'id', children: 'children' }"
                :placeholder="moveForm.getFieldValue('deptId') ? '请选择负责人' : '请选择部门'"
                style="width: 100%"
              />
            </a-form-item>
            <a-form-item label="备注" v-bind="formItemLayout">
              <a-textarea
                v-decorator="[
                  'remark',
                  { rules: [{ required: form.getFieldValue('type') === '其他', type: 'string', message: '请输入备注', whitespace: true }] }
                ]"
                placeholder="请输入备注"
                style="resize: none"
              />
            </a-form-item>
          </a-form>
          <template slot="footer">
            <a-button @click="showMove = false">取消</a-button>
            <a-button :loading="sending" @click="handleMove">确定</a-button>
          </template>
        </a-modal>
        <!-- 操作弹窗 end -->

        <!-- 二维码弹窗 -->
        <a-modal
          v-model="showQrCode"
          title="二维码"
          centered
          width="498px"
          :footer="null"
        >
          <qrcode-vue :value="j" size="450" render-as="svg" />
        </a-modal>
        <!-- 二维码弹窗 foot -->

      </a-spin>
    </a-card>
  </page-view>
</template>

<script>
import { mapState } from 'vuex'
import { PageView, STable, PDFModal, TeacherSelect } from '@/components'
import QrcodeVue from 'qrcode.vue'

const headerData = [
  { label: '物品名称', key: 'name' },
  { label: '分类', key: 'categories' },
  { label: '规格型号', key: 'model' },
  { label: '单位', key: 'unit' },
  { label: '固定资产库', key: 'quantity' },
  { label: '区域资产库', key: 'areaQty' }
]
const keyStrMaps = {
  name: '物品名称',
  // model: '规格型号',
  categories: '分类'
  // unit: '单位'
}
const personList = ['李某', '陈某', '王某']

export default {
  name: 'Detail',
  components: { PageView, STable, PDFModal, TeacherSelect, QrcodeVue },
  inject: ['formItemLayout'],
  props: {
    id: {
      type: [String, Number],
      default: ''
    }
  },

  validate ({ params }) { return !!params.id },

  async fetch ({ store, app }) {
    const { $get, dispatch } = store
    dispatch('property/getItemTypes')
    const list = []
    if (!$get(store, 'state.basic.deptList.length')) list.push({ fn: app.$departmentListFunc })
    if (!$get(store, 'state.basic.areaList.length')) list.push({ fn: app.$areaListFunc })
    await app.$requestList(list)
    dispatch('basic/setDeptArea')
  },

  async asyncData ({ $axios, params, app }) {
    const { $get } = app
    const data = { itemData: {}}
    const { id } = params
    await $axios.get(`api/assetsGoods/${id}`).then(res => {
      const { itemData } = data
      Object.assign(itemData, $get(res, 'data.data', {}))
      itemData.categories = [itemData.firId, itemData.secId]
    })
    return data
  },

  data () {
    return {
      j: 'http://192.168.1.119:3010/checkItem?j={"标题":1,"title":2}',
      sending: false,
      secTypeSending: false,

      showEdit: false,
      form: this.$form.createForm(this),

      showMove: false,
      moveType: 1,
      moveForm: this.$form.createForm(this),
      personList,

      showQrCode: false,

      showElse: false,
      target: {},
      showPDF: false,
      fileName: '',
      url: '',
      modalTitle: '',
      modalText: '',

      headerData,
      editable: false,
      tempValue: '',

      imageUrl: '',

      logColumns: [
        { title: '库存类型', width: '8%', align: 'center', dataIndex: 'ridType' },
        { title: '关联单号', align: 'center', dataIndex: 'sn' },
        { title: '关联类型', width: '8%', align: 'center', dataIndex: 'applyType' },
        { title: '申请人', width: '8%', align: 'center', dataIndex: 'userName' },
        { title: '经办人', width: '8%', align: 'center', dataIndex: 'handlerName' },
        { title: '变更数', align: 'center', dataIndex: 'quantity' },
        { title: '变更日期', align: 'center', dataIndex: 'updatedDate' },
        { title: '有效日期', align: 'center', dataIndex: 'activeDate' },
        { title: '备注', align: 'center', dataIndex: 'remark' },
        { title: '操作', width: '176px', align: 'center', scopedSlots: { customRender: 'action' }}
      ],
      queryParam: {
        pageSize: 10,
        pageNum: 1
      },
      count: 0,

      infoColumns: [
        { title: '使用部门', align: 'center', dataIndex: 'deptName' },
        { title: '使用区域', align: 'center', scopedSlots: { customRender: 'areaName' }},
        { title: '物品数量', align: 'center', dataIndex: 'quantity' },
        { title: '操作', width: '102px', align: 'center', scopedSlots: { customRender: 'action' }}
      ]
    }
  },

  computed: {
    ...mapState({
      firTypeList: state => state.property.itemFirTypeList,
      itemSecTypeListMaps: state => state.property.itemSecTypeListMaps,
      firTypeMaps: state => state.property.itemFirTypeMaps,
      secTypeMaps: state => state.property.itemSecTypeMaps,
      areaMaps: state => state.basic.areaMaps,
      deptList: state => state.basic.deptList,
      deptMaps: state => state.basic.deptMaps,
      deptListMaps (state) {
        const { $get, $clonedeep } = this
        const obj = $clonedeep(state.basic.deptListMaps)
        for (const id in obj) {
          const arr = obj[id]
          arr.forEach(i => {
            const { userId, userName, children } = i
            if (!$get(i, 'children.length')) Object.assign(i, { id: userId, name: userName })
            else children.forEach(c => Object.assign(c, { id: c.userId, name: c.userName }))
          })
        }
        console.log(obj)
        return obj
      },
      deptAreaList: state => {
        const { deptListMaps = {}, areaListMaps = {}} = state.basic
        const list = []
        for (const deptId in deptListMaps) {
          const arr = deptListMaps[deptId] || []
          list.push(...arr.map(i => Object.assign({}, i, { children: areaListMaps[i.areaId] })))
        }
        return list
      }
    })
  },

  watch: {
    'itemData.images': {
      handler (url) {
        this.imageUrl = url
      },
      immediate: true
    },

    showEdit (bool) {
      this.form.resetFields()
    },

    showMove (bool) {
      if (!bool) this.moveForm.resetFields()
    }
  },

  methods: {
    tabchange (e) {
      const name = ['logTable', 'infoTable'][e]
      const table = this.$refs[name]
      table && table.refresh && table.refresh()
    },

    checkQrcode (item) {
      const { $get, itemData, firTypeMaps, secTypeMaps } = this
      this.j = undefined
      const json = {}
      json['物品名称'] = itemData.name || '-'
      json['物品分类'] = itemData.categories.map((i, k) => $get([firTypeMaps, secTypeMaps][k], `${i}.name`, '')).join(' > ')
      json['物品编号'] = itemData.code || '-'
      json[`${item.ridType}数量`] = item.quantity || '-'
      json[`${item.ridType}日期`] = item.updatedDate || '-'
      json['关联单号'] = item.sn || '-'
      json['申请人'] = item.userName || '-'
      json['经办人'] = item.handlerName || '-'
      this.j = `${window.location.origin}/qrcode?j=${JSON.stringify(json)}`
      console.log(this.j)
      this.showQrCode = true
    },

    // 修改库存时改变类型
    typeChange (type) {
      if (type === '报废') this.form.setFieldsValue({ attr: 0 })
    },

    handlePage (p) {
      this.$handlePage(p)
    },

    infoLoadData (parameter) {
      const { id, $axios, $get, areaMaps } = this
      const params = { pageNum: -1, goodsId: id / 1 }
      const data = []

      return new Promise((resolve, reject) => {
        $axios.post('api/assetsGoodsDetail/query', params).then(res => {
          data.push(...$get(res, 'data.data.dataList', []).map(i => Object.assign(i, { areaPid: $get(areaMaps, `${i.areaId}.areaPid`) })))
          resolve({ data })
        }).catch(e => resolve({ data }))
      })
    },

    logLoadData (parameter) {
      const { id, queryParam, $axios, $get, logColumns, $moment } = this
      const params = { goodsId: id / 1 }
      const data = []
      for (const key in queryParam) {
        const item = queryParam[key]
        if (item) params[key] = item
      }

      return new Promise((resolve, reject) => {
        $axios.post('api/assetsGoodsLog/query', params).then(res => {
          data.push(...$get(res, 'data.data.dataList', []).map(item => {
            const { createdTime, effectiveTime, attr, quantity } = item
            logColumns.forEach(i => {
              const { dataIndex } = i
              if (!dataIndex) return false
              if (!item[dataIndex] && !(/0/.test(item[dataIndex]))) Object.assign(item, { [dataIndex]: '-' })
            })
            console.log('createdTime', createdTime)
            const updatedDate = createdTime && createdTime !== '-' ? $moment(createdTime).format('YYYY.MM.DD') : '-'
            const activeDate = effectiveTime && effectiveTime !== '-' ? $moment(effectiveTime).format('YYYY.MM.DD') : '-'
            return Object.assign(item, { updatedDate, activeDate, quantity: `${['-', '+'][attr]}${quantity}` })
          }))
          this.count = $get(res, 'data.data.count', 0)
          resolve({ data })
        }).catch(e => resolve({ data }))
      })
    },

    handleMove () {
      const { submitMove } = this
      this.moveForm.validateFields((err, values) => {
        if (err) return false
        submitMove(values)
      })
    },

    async submitMove (values) {
      this.$toggleSending(1)
      const param = values
      const { target, moveType, $axios, $get, $message, refresh, moveForm } = this
      param.id = target.id
      if ($get(param, 'areaId.length')) param.areaId = param.areaId[param.areaId.length - 1]
      if ($get(param, 'userId.length')) param.userId = param.userId.pop()
      param.type = ['报废', '转移'][moveType]
      const res = await $axios.put('api/assetsGoodsDetail/stock', param).then(res => res).catch(e => false)
      $message.destroy()
      if ($get(res, 'data.code') === '000000') {
        $message.info('操作成功')
        this.showMove = false
        refresh()
        moveForm.resetFields()
      } else $message.error($get(res, 'data.mesg', '请稍后再试'))
      this.$toggleSending()
    },

    async refresh () {
      const { id, itemData, $refs, $axios, $get } = this
      this.$toggleSending(1)
      const { infoTable, logTable } = $refs
      infoTable && infoTable.refresh()
      logTable && logTable.refresh()
      await $axios.get(`api/assetsGoods/${id}`).then(res => {
        Object.assign(itemData, $get(res, 'data.data', {}))
        itemData.categories = [itemData.firId, itemData.secId]
      })
      this.$toggleSending()
    },

    // 修改库存校验
    handleOk () {
      const { form, changeStock } = this
      form.validateFields((err, values) => {
        if (err) return false
        changeStock(values)
      })
    },

    // 修改库存请求
    async changeStock (values) {
      const { id, itemData, $axios, $message, $get } = this
      this.$toggleSending(1)
      const param = { id, ...values }
      const res = await $axios.put('api/assetsGoods/stock', param).then(res => res).catch(e => false)
      if ($get(res, 'data.code') === '000000') {
        await $axios.get(`api/assetsGoods/${id}`).then(res => {
          const data = $get(res, 'data.data', {})
          data.categories = [itemData.firId, itemData.secId]
          Object.assign(itemData, data)
        })
        $message.info('修改成功')
        this.showEdit = false
      } else $message.error($get(res, 'data.mesg', '请稍后再试'))
      this.$toggleSending(0)
    },

    checkPDF (item) {
      const types = ['出库', '入库', '报修', '其他']
      const titles = ['领料', '物品', '']
      const texts = ['申请', '申购', '报修']
      const index = types.indexOf(item.type)

      if (index < 3) {
        if (item.id === -1) return false
        const name = titles[index] || '查看报表'
        const action = texts[index] || ''

        this.modalTitle = `${name}${action}单`
        this.modalText = `${action}状态：审批完成`
        this.url = ''
        this.fileName = ''

        this.$toggleSending(1)
        this.$axios({
          url: `api/assetsApply/down/${item.id}`,
          responseType: 'arraybuffer',
          method: 'get',
          contentType: 'application/pdf;charset=utf-8'
        }).then(res => {
          if (!res.data.code) {
            const blob = new Blob([res.data], { type: 'application/pdf;charset=utf-8' })
            this.url = window.URL.createObjectURL(blob)
            this.fileName = `${name}${action}单_${Date.now()}`
            this.showPDF = true
            this.$toggleSending()
          }
        }).catch(e => [])
      } else {
        this.showElse = true
        Object.assign(this.target, item)
      }
    },

    /**
     * 上传图片
     */
    async handleUpload ({ file, onError, onSuccess }) {
      const { id, itemData, $message, $axios, $get } = this
      if (!file) return $message.error('无法上传')

      this.$toggleSending(1)
      const token = await this.$getQinuiToken()
      if (!token) {
        $message.destroy()
        $message.error('请稍后再试')
        this.$toggleSending()
      }

      const images = await this.$uploadImage(token, { file, onError, onSuccess })
      $message.destroy()
      if (!images) $message.error('请稍后再试')
      const res = await $axios.put(`api/assetsGoods/${id}`, { images }).then(res => res).catch(e => false)
      if ($get(res, 'data.code', -1) === '000000') {
        $message.info('修改成功')
        Object.assign(itemData, { images })
      } else $message.error($get(res, 'data.mesg', '请稍后再试'))
      this.$toggleSending()
    },

    beforeUpload (file) {
      // const isJPG = file.type === 'image/jpeg'
      // if (!isJPG) {
      //   this.$message.error('You can only upload JPG file!')
      // }
      const isJPG = true
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isLt2M) {
        this.$message.error('Image must smaller than 2MB!')
      }
      return isJPG && isLt2M
    },

    handleAction (item, type) {
      this.target = item
      this.moveType = type
      this.showMove = true
    },

    async handleExport () {
      const { id, queryParam, itemData, $get } = this
      this.$toggleSending(1)
      const param = { ...queryParam }
      param.goodsId = id / 1
      delete param.pageSize
      param.pageNum = -1
      const fileName = `${$get(itemData, 'name') || ''}物品日志_${Date.now()}`
      await this.$exportFile({ url: 'api/assetsGoodsLog/export', param, fileName })
      this.$toggleSending()
    },

    editCount () {
      this.showEdit = true
    },

    // 点击编辑按钮，编辑信息
    handleEdit () {
      this.editable = true
      this.tempValue = { ...this.itemData }
      delete this.tempValue.fixedCount
      delete this.tempValue.areaCount
    },

    // 修改信息
    async handleSave () {
      const { id, tempValue, itemData, $message, handleCancel, $get, $axios } = this
      const param = { id, unit: tempValue.unit, model: tempValue.model }
      for (const key in tempValue) {
        const item = tempValue[key]
        if (!keyStrMaps[key]) continue
        if (!$get(item, 'length') || (typeof item === 'string' && !item.trim())) {
          $message.destroy()
          $message.error(`${keyStrMaps[key]}不能为空`)
          return
        } else {
          if (key === 'categories') {
            tempValue[key].forEach((i, k) => (param[['firId', 'secId'][k]] = i))
          } else param[key] = tempValue[key]
        }
      }
      this.$toggleSending(1)
      const res = await $axios.put(`api/assetsGoods/${id}`, param).then(res => res).catch(e => false)
      this.$toggleSending()
      $message.destroy()
      if ($get(res, 'data.code', -1) === '000000') {
        handleCancel()
        $message.info('修改成功')
        Object.assign(itemData, param)
      } else $message.error($get(res, 'data.mesg', '请稍后再试'))
    },

    handleCancel () {
      this.editable = false
      this.tempValue = {}
    },

    goback () {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
  @item-height: 60px;
  @img-container-height: 180px;
  @img-height: 164px;

  div.header-container {
    .Flex;
    .Flex-align-center;
    .Flex-wrap;

    /deep/ .image-container .ant-upload {
      width: unset !important;
      height: @img-container-height !important;
      margin-bottom: 0 !important;
      white-space: nowrap !important;
      overflow: hidden !important;

      .ant-upload-text {
        width: @img-container-height !important;
      }

      img {
        max-width: 100% !important;
        width: unset !important;
        height: @img-height !important;
      }
    }

    .ant-row.ant-form-item {
      border: 1px solid rgba(211, 211, 211, .45);
      background: rgba(211, 211, 211, .15);
      margin-bottom: 0;

      &.form-item-height {
        height: @item-height;
        .Flex;
        .Flex-align-center;
      }
    }

    .editing {
      .Flex;
      .Flex-align-center;
    }
  }

  .btn-container {
    button {
      margin-top: 20px;
      margin-bottom: 20px;
    }
  }

  .width-fix {
    width: 50%;
  }
</style>
